class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None


class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        self.node = None

        def search(node):
            left_flag = False
            right_flag = False
            if node.left:
                left_flag = search(node.left)
            if node.right:
                right_flag = search(node.right)
            if node == p or node == q:
                if left_flag or right_flag:
                    self.node = node
                return True
            else:
                if left_flag and right_flag:
                    self.node = node
                if left_flag or right_flag:
                    return True
                else:
                    return False

        search(root)
        return self.node
